package cn.com.libertymutual.sys.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import cn.com.libertymutual.core.web.util.RequestUtils;

@Component
@RefreshScope // 刷新配置无需重启服务
public class NioClient {
	private Logger log = LoggerFactory.getLogger(getClass());
	
	/**
	file:
		  transfer:
		    address: 10.132.21.168:19999,10.132.22.168:19999
		    dsts: /app/chuxingbao/web/sticcxb/upload/sftp/,/app/chuxingbao/web/sticcxb/upload/sftp/
		    uploadImagesPath: /app/chuxingbao/web/sticcxb/upload/sftp/
		    uploadImagesReportCase: /app/chuxingbao/web/sticcxb/upload/images_report_case/
		    uploadHeadimgPathUsers: /app/chuxingbao/web/sticcxb/upload/userHeadImg/users/
		    bankImgPathDefault: /app/chuxingbao/web/sticcxb/upload/assets/x3/banks/
		    userHeadImgPathDefault: upload/userHeadImg/default/
		    headImgDefault: headImgDefault.jpg
	**/
	
	@Value("#{'${file.transfer.address}'.split(',')}")
	private String[] hosts;
	
	@Value("#{'${file.transfer.dsts}'.split(',')}")
	private String[] dsts;
	
	@Value("${file.transfer.timeout:6000}")
	private int timeout;

	private String thisIP = null;
	
	@PostConstruct
	public void init() {

		log.info("------hostss---{}--------{}", hosts[0], hosts[1]);
		

		thisIP = RequestUtils.getLocalHostLANAddress()[0];

		log.info("------thisIP-----------{}", thisIP);
		
	}
	
	public void upload( String fileName, String reomteFilePath ) {
		SocketChannel socketChannel = null;
		FileChannel fileChannel = null;
		ByteBuffer buffer = null;
		ByteBuffer buffer2 = null;
		String hostIp = null;
		for (int i = 0; i < hosts.length; i++) {
			
			hostIp = hosts[i].substring(0, hosts[i].lastIndexOf(":"));
			
			if( thisIP.equals( hostIp ) ) {
				log.info("本机服务器{}，不用上传.", thisIP);
				continue;
			}

			try {
				socketChannel = SocketChannel.open();  
				socketChannel.socket().connect(new InetSocketAddress(hostIp, Integer.parseInt(hosts[i].substring(hosts[i].lastIndexOf(":")+1))), timeout);
				
				
				File file = new File( fileName );
	            if( !file.exists() ) {
	            	log.info("文件{}不存在", fileName);
	            	throw new RuntimeException("上传文件不存在");
	            }
		        
	            
	            fileChannel = new FileInputStream(file).getChannel();  
	            buffer = ByteBuffer.allocate(1024*512);  
	            socketChannel.read(buffer);  
	            buffer.flip();
	            log.info("==={}", new String(buffer.array(), 0, buffer.limit(), Charset.forName("utf-8")));  
	            buffer.clear();
	            log.info("远程路径名：{}",dsts[i]+reomteFilePath+ File.separator + file.getName());
	            byte[] head =  (dsts[i]+reomteFilePath +File.separator+ file.getName()).getBytes();
	            buffer2 = ByteBuffer.allocate(128);
	            buffer2.put(String.format("%03d", head.length).getBytes());
	            buffer2.put( head );
	            buffer2.flip();  
	            log.info("------{}", new String( buffer2.array(), 0, buffer2.limit(), Charset.forName("utf-8") ) );
	            socketChannel.write(buffer2);
	            buffer2.clear();
	            buffer2 = null;
	            ///buffer.flip();
	       
	            int num = 0;
	            while ((num=fileChannel.read(buffer)) > 0) {
	                buffer.flip();
	                socketChannel.write(buffer);
	                buffer.clear();
	            }
	            if (num == -1) {
	                fileChannel.close();
	                fileChannel = null;
	                socketChannel.shutdownOutput();  
	            }
	            // 接受服务器  
	            socketChannel.read(buffer);  
	            buffer.flip();
	            log.info("{}", buffer.limit() );
	            log.info(new String(buffer.array(), 0, buffer.limit(), Charset.forName("utf-8")));  
	            buffer.clear();  
	            
			}
			catch (IOException e) {
				log.error("连接{}:{}错误", hostIp, hosts[i].substring(hosts[i].lastIndexOf(":")+1) );
	            log.error("传输文件错误"+fileName, e);
	            throw new RuntimeException("传输文件错误", e);
	        }
			finally {
				if( fileChannel != null ) {
					try {
						fileChannel.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if( socketChannel != null ) {
					try {
						socketChannel.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if( buffer != null ) {
					buffer.clear();
					buffer = null;
				}
				if( buffer2 != null ) {
					buffer2 = null;
				}
			}
		}
	}
	
	public static int FLAG = 0;
	public static void main(String[] args) {
		/*
		ByteBuffer buffer2 = ByteBuffer.allocate(100);
		byte[] str = "abcdefg.txt".getBytes();
		
		buffer2.position(3);
		buffer2.put(str);
		
		buffer2.position(0);
		
		buffer2.put(String.format("%03d", str.length).getBytes());
		
		System.out.println( new String( buffer2.array() ) );
		*/
        for (int i = 0; i < 500; i++) {
        	
            // 模拟三个发端  
            new Thread() {  
                public void run() {
                    try {  
                        SocketChannel socketChannel = SocketChannel.open();  
                        socketChannel.socket().connect(new InetSocketAddress("10.132.28.243", 19999), 5000);
                        FLAG++;
                        File file = new File("E:\\bob.png");  
                        FileChannel fileChannel = new FileInputStream(file).getChannel();  
                        ByteBuffer buffer = ByteBuffer.allocate(1024*1024);  
                        socketChannel.read(buffer);
                        buffer.flip();
                        System.out.println("==="+new String(buffer.array(), 0, buffer.limit(), Charset.forName("utf-8")));  
                        buffer.clear();
                        final
                        byte[] kkk = ("E:\\image\\"+System.currentTimeMillis()+Math.random()+"-"+FLAG+".png").getBytes();
                        ByteBuffer buffer2 = ByteBuffer.allocate(100);
                        buffer2.put(String.format("%03d", kkk.length).getBytes());
                        buffer2.put( kkk );
                        buffer2.flip();  
                        System.out.println("------------"+ new String( buffer2.array(), 0, buffer2.limit(), Charset.forName("utf-8") ) );
                        socketChannel.write(buffer2);
                        buffer2.clear();
                        ///buffer.flip();
                   
                        
                        
                        
                        int num = 0;  
                        while ((num=fileChannel.read(buffer)) > 0) {  
                            buffer.flip();                        
                            socketChannel.write(buffer);  
                            buffer.clear();  
                        }  
                        if (num == -1) {  
                            fileChannel.close();  
                            socketChannel.shutdownOutput();  
                        }  
                        // 接受服务器  
                        socketChannel.read(buffer);  
                        buffer.flip();
                        System.out.println( buffer.limit() );
                        System.out.println(new String(buffer.array(), 0, buffer.limit(), Charset.forName("utf-8")));  
                        buffer.clear();  
                        socketChannel.close();
                        Thread.sleep(10);
                    } catch (Exception e) {  
                        e.printStackTrace();  
                    }  
                      
                };  
            }.start();  
              
        }  
        Thread.yield();  
    }  
}
